package com.example.qa_back.utils;

import com.example.qa_back.entity.CollectQuestion;
import com.example.qa_back.entity.QA;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author 董帅
 * @date 2021/3/6 - 20:41
 */

/*
* 功能：导出数据库中的QA对
* */
public class HandleExcelExport {
    public static Integer exportQAs(String filePath, List<String> titles, List<QA> qaList, String sheetName) {
        int flag = 1;
        Workbook workbook = null;
        workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(sheetName);
        int rowIndex = 0;
        Row titleRow = sheet.createRow(rowIndex);
        for (int i = 0; i < titles.size(); ++i) {
            titleRow.createCell(i).setCellValue(titles.get(i));
        }
        ++rowIndex;
        Row row = null;
        Cell cell;
        String question, answer;
        for (QA qa : qaList) {
            question = qa.getQuestion();
            answer = qa.getAnswer();
            row = sheet.createRow(rowIndex);
            row.createCell(0).setCellValue(question);
            row.createCell(1).setCellValue(answer);
            ++rowIndex;
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
        } catch (IOException e) {
            flag = 0;
            e.printStackTrace();
        }
        return flag;
    }

    public static Integer exportCQs(String filePath, List<String> titles, List<CollectQuestion> qList, String sheetName) {
        int flag = 1;
        Workbook workbook = null;
        workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(sheetName);
        int rowIndex = 0;
        Row titleRow = sheet.createRow(rowIndex);
        for (int i = 0; i < titles.size(); ++i) {
            titleRow.createCell(i).setCellValue(titles.get(i));
        }
        ++rowIndex;
        Row row = null;
        Cell cell;
        String question;
        for (CollectQuestion q : qList) {
            question = q.getQuestion();
            row = sheet.createRow(rowIndex);
            row.createCell(0).setCellValue(question);
            ++rowIndex;
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
        } catch (IOException e) {
            flag = 0;
            e.printStackTrace();
        }
        return flag;
    }
}
